package cn.jhc.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.jhc.bean.CartItem;
import cn.jhc.bean.Title;
import cn.jhc.bean.UserCookie;
import cn.jhc.bean.User;
import cn.jhc.dao.TitleDAO;

/**
 * Servlet implementation class ShowShoppingCartServlet
 */
@WebServlet("/user/showcart.do")
public class ShowShoppingCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShowShoppingCartServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		User user = (User)request.getSession().getAttribute("currentUser");
		
		List<CartItem> cart = new ArrayList<>();
		List<CartItem> list = new ArrayList<>();
		Cookie[] cookies = request.getCookies();
		Cookie c = UserCookie.tranversal(cookies, user.getLoginname());
		if (c != null) 
		{
			cart = UserCookie.getCartItems(c);
			TitleDAO dao = new TitleDAO();
			for (CartItem cItem : cart) 
			{
				String isbn = cItem.getIsbn();
				Title title = dao.findByIsbn(isbn);
				double price = title.getPrice();
				String imageFile = title.getImageFile();
				String t = title.getTitle();
				int num = cItem.getNum();
				list.add(new CartItem(isbn, t, imageFile, price, num));
			}
		}

		request.setAttribute("cart", list);
		//跳转到购物车jsp
		request.getRequestDispatcher("/shoppingCar.jsp").forward(request, response);
		
	}

}

